package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.bean.Question;
import com.example.demo.bean.Word;
import com.example.demo.service.QuestionService;
import com.example.demo.service.WordService;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Jim Chen
 * @date 2021-04-15
 */
@RestController
@RequestMapping("/question")
public class QuestionController {

    @Autowired
    private QuestionService questionService;

    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public JSONArray list(HttpServletRequest request){
        JSONArray result = new JSONArray();
        List<Question> questions = questionService.findAll();
        for (Question question : questions) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("questionId", question.getId());
            jsonObject.put("questionTitle", question.getQuestion());
            jsonObject.put("questionImage", "setu");
            jsonObject.put("questionAnswer", question.getAnswer());
            jsonObject.put("questionType", 0); //0 单选， 1 多选
            JSONArray jsonArray = new JSONArray();
            JSONObject optionA = new JSONObject();
            optionA.put("optionId", 1);
            optionA.put("context", question.getOptionA());

            JSONObject optionB = new JSONObject();
            optionB.put("optionId", 2);
            optionB.put("context", question.getOptionB());

            JSONObject optionC = new JSONObject();
            optionC.put("optionId", 3);
            optionC.put("context", question.getOptionC());

            JSONObject optionD = new JSONObject();
            optionD.put("optionId", 4);
            optionD.put("context", question.getOptionD());

            jsonArray.add(optionA);
            jsonArray.add(optionB);
            jsonArray.add(optionC);
            jsonArray.add(optionD);

            jsonObject.put("questionOptions", jsonArray);
            result.add(jsonObject);
        }

        return result;
    }

    @GetMapping(value = "/next/{id}")
    @ResponseBody
    public Question next(HttpServletRequest request, @PathVariable("id") String id){
        return questionService.getNext(Integer.valueOf(id) + 1);
    }
}
